import * as _ from "lodash";

/**
 * 切换主题
 * @param {*} theme
 */
export function setTheme(theme, color, menu) {
    const html = document.documentElement;
    const classList = html.classList;

    if (theme && color) {
        if (!menu) {
            if (theme == "default") {
                menu = "default";
            } else {
                menu = "dark";
            }
        }
        classList.value = `theme-${theme} color-${color} menu-${menu}`;
    }
}

/**
 * 是否是手机号
 * @param {} val
 * @returns
 */
export function isPhone(val) {
    return val.match(/^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/);
}

// 遍历对象及子元素
export function loop(item, func, parent) {
    if (!item || !func) {
        return;
    }

    if (_.isArray(item)) {
        for (var i in item) {
            let subItem = item[i];
            let b = loop(subItem, func, parent);
            if (b) {
                // 中断执行
                return true;
            }
        }
        return;
    }

    let b = func(item, parent);
    if (b) {
        // 中断执行
        return true;
    }
    return loop(item.children, func, item);
}

// 从树中删除符合条件的元素
export function removeFromTree(tree, predicate) {
    let removed = _.remove(tree, predicate);
    if (removed && removed.length) {
        return true;
    }

    // 当前层级没找到，则继续处理下一层级的数据
    for (var i in tree) {
        let sub = tree[i];
        if (!sub.children) {
            continue;
        }

        removed = removeFromTree(sub.children, predicate);
        if (removed) {
            return true;
        }
    }

    return false;
}
